﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using GzipManagerPro.UI.Controls.Preview;
using GzipManagerPro.UI.Dialogs;
using GzipManagerPro.IO;
using GzipManagerPro.UI.Utility;

namespace GzipManagerPro.UI.CommandLine
{
    public class Parser
    {
        private string[] Arguments;
        private Dictionary<string, Action> Decisions;

        public Action Action { get; private set; }
        public string Path { get; private set; }

        public Parser(string[] arguments)
        {
            this.Action = CommandLine.Action.None;

            if (arguments == null || arguments.Length == 0)
                return;

            this.Arguments = arguments;
            this.Decisions = new Dictionary<string, Action>();

            this.Decisions.Add("^[/\\-][aA]$", Action.AddToArchive);
            this.Decisions.Add("^[/\\-][eE]$", Action.ExtractArchive);
            this.Decisions.Add("^[/\\-][?]$", Action.ShowHelp);

            System.Text.RegularExpressions.Regex regex = null;
            foreach (var argument in this.Arguments)
            {
                if (System.IO.File.Exists(argument) || Directory.Exists(argument))
                {
                    this.Path = argument;
                    if (this.Action == CommandLine.Action.None)
                        this.Action = CommandLine.Action.ViewArchive;

                    continue;
                }

                foreach (var key in this.Decisions.Keys)
                {
                    regex = new System.Text.RegularExpressions.Regex(key);
                    if (regex.IsMatch(argument, 0))
                        this.Action = this.Decisions[key];
                    
                }
                
            }

        }

        public void Execute()
        {
            switch (this.Action)
            {
                case CommandLine.Action.None:

                    Application.Run(new MainForm());
                    break;

                case CommandLine.Action.ShowHelp:

                    "/a: add item to archive /e: extract passed archive to".Information("Commandline Help");
                    break;

                
                case CommandLine.Action.ExtractArchive:

                    Utility.Helper.ExtractTo(this.Path);

                    break;

                case CommandLine.Action.AddToArchive:

                    Utility.Helper.AddToArchive(this.Path);

                    break;

                case CommandLine.Action.ViewArchive:


                    Application.Run(new MainForm(this.Path));
                    break;
            }
        }
    }

    public enum Action
    {
        None,
        ViewArchive,
        AddToArchive,
        ExtractArchive,
        ShowHelp
    }
}
